import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm, Tag } from "antd";
import {
  createCategory,
  updateCategory,
  deleteCategory,
  listCategories,
} from "../../api/ckgl";
import CategoryModal from "./componets/CategoryModal";

const ListCategories = () => {
  const [categoryList, setCategoryList] = useState<any[]>([]);
  const [totalCategories, setTotalCategories] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  const [isCategoryModalVisible, setIsCategoryModalVisible] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<any | null>(null);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "类别名称",
      dataIndex: "category_name",
      key: "category_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (type: number) =>
        type === 1 ? (
          <Tag color="green">耗材</Tag>
        ) : (
          <Tag color="red">非耗材</Tag>
        ),
    },
    {
      title: "操作",
      dataIndex: "op",
      key: "op",
      render: (_: any, record: any) => (
        <>
          <Button type="link" onClick={() => handleEditCategory(record)}>
            编辑种类
          </Button>
          <Popconfirm
            okText="确定"
            cancelText="取消"
            title="确定删除物品类别"
            onConfirm={() => handleDeleteCategory(record)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleDeleteCategory = (record: any) => {
    // 调用 deleteCategory API，并处理响应
    deleteCategory({
      category_id: record.id,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      message.success(`物品类别 "${record.category_name}" 删除成功`);
      // 更新当前页
      reset(currentPage);
    });
  };

  const handleEditCategory = (record: any) => {
    setCurrentCategory(record);
    setIsCategoryModalVisible(true);
  };

  const getListCategories = (page: number) => {
    // 调用 listCategories API，并处理响应
    listCategories({
      page,
      size: pageSize,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { categories, total } = res.data;
      setCategoryList(categories);
      setTotalCategories(total);
    });
  };

  const reset = (page: number) => {
    getListCategories(page);
  };

  const handleCategoryModalOk = async (values: any) => {
    // 根据情况调用 createCategory 或 updateCategory API，并处理响应
    if (currentCategory) {
      // 更新
      let msg = "更新成功";
      await updateCategory({
        category_id: currentCategory.id,
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    } else {
      // 添加
      let msg = "添加成功";
      await createCategory({
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    }
    reset(currentPage);
    setIsCategoryModalVisible(false);
  };

  useEffect(() => {
    getListCategories(currentPage);
  }, [currentPage]);

  return (
    <div>
      <Button
        style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
        onClick={() => {
          setIsCategoryModalVisible(true);
          setCurrentCategory(null);
        }}
        size="large"
        type="primary"
      >
        添加物品类别
      </Button>
      <Table
        dataSource={categoryList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalCategories,
        }}
      />
      <CategoryModal
        title={currentCategory ? "编辑物品类别" : "添加物品类别"}
        visible={isCategoryModalVisible}
        onCancel={() => setIsCategoryModalVisible(false)}
        onOk={handleCategoryModalOk}
        defaultValue={currentCategory || {}}
      />
    </div>
  );
};

export default ListCategories;
